// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <condition_variable>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>

#include <pollux/common/base/exceptions.h>
#include <pollux/common/future/pollux_promise.h>

namespace kumo::pollux {
    /// Similar to std::counting_semaphore in C++ 20.
    class Semaphore {
    public:
        Semaphore(int32_t count) : count_(count) {
        }

        // If count > 0, decrements count. Otherwise blocks until count is incremented
        // by release() from another thread.
        void acquire() {
            std::unique_lock l(mutex_);
            if (count_) {
                --count_;
            } else {
                ++numWaiting_;
                cv_.wait(l, [&]() { return count_ > 0; });
                --numWaiting_;
                --count_;
            }
        }

        /// Increments count. Releases one blocking call to acquire, if any.
        void release() {
            std::lock_guard<std::mutex> l(mutex_);
            ++count_;
            if (numWaiting_ > 0) {
                cv_.notify_one();
            }
        }

        int32_t count() {
            std::lock_guard<std::mutex> l(mutex_);
            return count_;
        }

    private:
        std::mutex mutex_;
        std::condition_variable cv_;
        volatile int32_t count_;
        volatile int32_t numWaiting_{0};
    };
} // namespace kumo::pollux
